package com.csu.petstore.controller;

import com.csu.petstore.log.Syslog;
import com.csu.petstore.pojo.Cart;
import com.csu.petstore.pojo.CartItem;
import com.csu.petstore.service.CartService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
@RequestMapping("/cart")
public class CartController {
    @Autowired
    private CartService cartService;
    @GetMapping("/cartForm")
    @Syslog(modelName = "购物车",methodDesc = "进入购物车界面",methodType = 2)
    public String index(HttpServletRequest request){
        HttpSession session = request.getSession();
        if (session.getAttribute("username") != null){
            String username = (String) session.getAttribute("username");
            Cart cart = cartService.getCart(username);
            session.setAttribute("cart" , cart);
        }

        return "/cart/cart";
    }

    @GetMapping("/removeCartItem")
    @Syslog(modelName = "购物车",methodDesc = "删除购物车物品",methodType = 2)
    public String deleteItem(@RequestParam("itemid")String itemId, HttpServletRequest request){
        HttpSession session = request.getSession();
        Cart cart1 = (Cart) session.getAttribute("cart");
        String username = cart1.getUserId();
        Cart cart = cartService.getCart(username);
        Cart cart2 = cartService.removeItemFromCart(cart , itemId , username);
        session.setAttribute("cart" , cart2);

        return "/cart/cart";
    }

    @GetMapping("/update")
    @ResponseBody
    public String update(@RequestParam("itemid")String itemid,@RequestParam("quantity") int Quantity, HttpServletRequest request){
        HttpSession session = request.getSession();
        Cart cart = (Cart) session.getAttribute("cart");
        String userId = cart.getUserId();
        cartService.updateQuantity(itemid,Quantity,userId);
        Cart cart1 = cartService.getCart(userId);
        session.setAttribute("cart",cart1);
        return cart1.getSubTotal().toString();
    }



}
